package com.hxexp.weixin.mvc.authenticode.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hxexp.weixin.common.cache.TokenCacheManager;
import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.constant.CookieName;
import com.hxexp.weixin.constant.StringConstant;
import com.hxexp.weixin.hpe.api.authenticode.model.AccountAuthenticodeResultBean;
import com.hxexp.weixin.hpe.api.login.model.LoginResultBean;
import com.hxexp.weixin.mvc.authenticode.service.AccountAuthenticodeService;

/**
 * 发送更新用户信息验证码控制器
 *
 * @author wang.bin
 * @author li.jiang
 */
@Controller
@RequestMapping(value = "/authenticode")
public final class AccountAuthenticodeController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountAuthenticodeController.class);

    @Autowired
    private TokenCacheManager tokenCacheManager;
    @Autowired
    private AccountAuthenticodeService accountAuthenticodeService;

    /**
     * 发送更新用户信息验证码的页面
     *
     * @param model
     * @return 发送更新用户信息验证码视图名
     */
    @RequestMapping(value = "/index")
    public String index(Model model) {
        return "send_accountcaptcha";
    }

    /**
     * 发送更新用户信息的验证码
     *
     * @param model
     * @return 验证码发送结果
     */
    @RequestMapping(value = "/sendcaptcha")
    @ResponseBody
    public AccountAuthenticodeResultBean sendCaptcha(String mobile,
                                                     @CookieValue(value = CookieName.TOKEN, defaultValue = StringConstant.BLANK) String token, Model model) {
        AccountAuthenticodeResultBean accountAuthenticodeResult = new AccountAuthenticodeResultBean();
        // 从缓存中获取登陆用户信息
        LoginResultBean loginResultBean = tokenCacheManager.getUserFromCache(token);
        String userId = loginResultBean.getUserId();
        try {
            accountAuthenticodeResult = accountAuthenticodeService.sendCaptcha(mobile, userId);
        } catch (ServiceException e) {
            LOGGER.error("调用更新用户信息验证码时发生异常", e);
        }

        return accountAuthenticodeResult;
    }
}
